package maa.action.admin.course;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.DAOCommand;
import maa.dao.DAOFactory;
import maa.dao.DAOManager;
import maa.database.ConnectionPool;
import maa.action.ActionException;
import maa.dao.DAOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class RemoveCourse implements Action {
    @Override
    public ActionResult execute(final HttpServletRequest req, HttpServletResponse resp) throws Exception {
        ActionResult actionResult = new ActionResult();
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        String string = req.getParameter("uuid").substring(0,req.getParameter("uuid").length()-1);
        final UUID uuid = UUID.fromString(string);
        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                Boolean flag;
                try {
                    flag = daoManager.getCourseDAO().delete(uuid);
                } catch (DAOException e) {
                    throw new ActionException("Exception in courseDAO.delete(uuid)");
                }
                return flag;
            }
        };
        Boolean res = (Boolean) daoManager.executeAndClose(command);
        if (res) {
            actionResult.setResult("admin-cabinet");
            actionResult.setRedirected(true);
        } else {
            req.setAttribute("course_delete_error", "Course removal failed");
            actionResult.setResult("admin-cabinet");
            actionResult.setRedirected(false);
        }
        return actionResult;
    }
}
